﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Koronkirskuri
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private double loan;
        private double intrestRate;
        private double timeLeft;
        private double monthsLeft;
        private double payment;


        public MainWindow()
        {
            InitializeComponent();
            Initialize();
        }

        private void Initialize()
        {
            loan = 0;
            intrestRate = 0;
            timeLeft = 0;
            payment = 0;
        }

        private void btnCalculate_Click(object sender, RoutedEventArgs e)
        {
            lbLoanList.Items.Clear();
            tbPayment.Text = "";
            if (LoadNums())
            {
                monthsLeft = timeLeft * 12;
                List<double> debt = Calculate();
                tbPayment.Text = payment.ToString();
                for (int i = 0; i < monthsLeft; i++)
                {
                    double temp = debt[debt.Count() -1] - payment * i;
                    lbLoanList.Items.Add("Erä "+ i +". Velkaa jäljellä: "+ temp.ToString());
                }
            }
        }

        private bool LoadNums()
        {
            if (!(double.TryParse(tbLoan.Text, out loan))) return false;
            if (!(double.TryParse(tbIntrest.Text, out intrestRate))) return false;
            if (!(double.TryParse(tbTime.Text, out timeLeft))) return false;
            return true;
        }

        private List<double> Calculate() 
        {
            List<double> debt = new List<double>();
            double percent = intrestRate / 100 +1;         

            if (intrestRate != 0)
            {
                debt.Add(loan * percent);
                payment = debt[debt.Count() - 1] / 12;
                for (int i = 1; i < timeLeft; i++)
                {
                    debt.Add(debt[debt.Count()-1] + (debt[debt.Count() -1] - payment) * (percent-1) );
                }
            }
            else
            {
                for (int i = 0; i < timeLeft; i++)
                {
                    debt.Add(loan);
                }
            }

            payment = debt[debt.Count() -1] / monthsLeft;

            return debt;
        }
    }
}
